package com.leyou.auth.service.impl;

import com.leyou.auth.client.UserClient;
import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.pojo.UserInfo;
import com.leyou.auth.service.AuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.user.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;

@Service
@EnableConfigurationProperties(JwtProperties.class)
public class AuthServiceImpl implements AuthService {

    @Autowired
    private JwtProperties prop;

    @Autowired
    private UserClient userClient;

    @Override
    public String login(String username, String password) {

        try {
            User user = userClient.queryUserByUsernameAndPassword(username, password);

            if (user == null) {
                throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
            }

            UserInfo userInfo = new UserInfo(user.getId(),username);
            PrivateKey privateKey = prop.getPrivateKey();
            int expireMinutes = prop.getExpireMinutes();

            String token = JwtUtils.generateToken(userInfo, privateKey, expireMinutes);

            return token;
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
    }
}
